package com.teacher.hong.filter;

import com.alibaba.fastjson.JSONObject;
import com.teacher.hong.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 用户登录过滤器
 */
@Slf4j
//@WebFilter("/*")
public class UserLoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //写一些过滤器的初始化时的代码。。。
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        log.debug("经过Token令牌过滤器，上一个过滤器传递过来的数据：" + servletRequest.getAttribute("name"));
        /* 在这里做Token认证
           如果认证通过，收放行请求至对应的Servlet，
           如果认证未通过，则拒绝请求，并返回提示信息
         */

        //通过向下转型，获取到HttpServletRequest和HttpServletResponse
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //先获取用户请求地址
        String uri = req.getRequestURI();
        log.debug("URI：" + uri);

        if (uri.startsWith("/api/webSocket") || uri.equals("/api/login") || uri.equals("/api/getVisits") || uri.startsWith("/api/my")) {
            //如果当前URI是登录接口，则直接放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //1. 先从header里面获取token令牌
        String token = req.getHeader("Token");

        //2. 使用TokenUtils进行验证
        Object sign = TokenUtils.verify(token);
        if (sign == null) {
            //说明令牌验证未通过
            JSONObject object = new JSONObject(true);
            object.put("state", 401);
            object.put("message", "Token验证未通过");
            object.put("timestamp", LocalDateTime.now());
            resp.setStatus(401);
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(object.toJSONString());
            return;
        }

        //放行，将servletRequest, servletResponse俩对象传递给下一个过滤器
        filterChain.doFilter(servletRequest, servletResponse);

    }

    @Override
    public void destroy() {
        //写一些过滤器的销毁时的代码。。。
    }

}
